import DomainMaker from "../../funcObj/interface/DomainMaker";
import GameManager from "../../manager/GameManager";
import Player from "../../player/Player";
import DestructibleFacility from "../DestructibleFacility";
import { Killer } from "../../funcObj/interface/HealthPoint";
import { Location, MapLength, blockSize } from "../../info/Predefine";
import { GamePropType } from "../../info/GameEnum";

const { ccclass, property } = cc._decorator;
/**
 * 领地扩张器
 */
@ccclass
export default class DomainExpander extends DestructibleFacility implements DomainMaker {

    myDomain: Location[];

    @property([cc.SpriteFrame])
    color: cc.SpriteFrame[] = [];

    init(player: Player): void {
        super.init(player);
        this.node.getChildByName("blue").getComponent(cc.Sprite).spriteFrame = this.color[this.player.playerId];
        this.myDomain = [];

        if (this.player.props[GamePropType.领地范围]) {
            this.resetViewAndDomain(6);
        } else {
            this.resetViewAndDomain(4);
        }
    }

    /**
     * 增加地盘和视野
     * @param extend 延伸多少格
     */
    resetViewAndDomain(extend: number) {
        let selfPositon = this.node.position;
        let minX = this.locations[0].locationX;
        let maxX = this.locations[0].locationX;
        let minY = this.locations[0].locationY;
        let maxY = this.locations[0].locationY;
        this.locations.forEach((location) => {
            if (location.locationX < minX) minX = location.locationX;
            if (location.locationX > maxX) maxX = location.locationX;
            if (location.locationY < minY) minY = location.locationY;
            if (location.locationY > maxX) maxY = location.locationY;
        })

        let startX = Math.max(0, minX - extend);
        let endX = Math.min(maxX + extend, MapLength - 1);
        let startY = Math.max(0, minY - extend);
        let endY = Math.min(MapLength - 1, maxY + extend);

        let tempLocations: Location[] = [];
        for (let x = startX; x <= endX; x++) {
            for (let y = startY; y <= endY; y++) {
                let location = { locationX: x, locationY: y };
                let position = GameManager.instance.getGamePosition(location);
                if (position.sub(selfPositon).mag() < extend * blockSize) {
                    tempLocations.push(location);
                }
            }
        }

        this.myDomain = tempLocations;
        this.player.onGetNewDomain(this.myDomain);
    }

    die(killer: Killer): void {
        super.die(killer);
        let myDomain = this.myDomain;
        this.myDomain = null;
        this.player.loseDomain(myDomain);
    }
}
